<template>
  <div class="addWares-page">
    <div class="addWares-scroll" :class="{ 'addWares-height' : showPicker }">
      <div class="item-module">
        <h2>上传照片<span class="icon">*</span><span class="text">好的照片能帮你促进交易</span></h2>
        <div class="imageUpload">
          <image-upload 
            :value.sync="fileList"
            :maximum="config.limit"
            :id="config.id"
          />
        </div>
      </div>
      <div class="item-module">
        <h2>标题<span class="icon">*</span></h2>
        <div class="input-value">
          <input type="text" v-model="params.title" @blur="blurHandler" maxlength="30" placeholder="请输入标题" />
        </div>
      </div>
      <div class="item-module">
        <h2>{{ config.descTitle }}<span class="icon">*</span></h2>
        <div class="input-value">
          <textarea v-model="params.description" :maxlength="config.maxlength" @blur="blurHandler" placeholder="请输入描述" />
          <span class="limit">{{ params.description.length + '/' + config.maxlength }}</span>
        </div>
        <div class="show-btn" v-show="config.visibleBtn && !config.isVisible" @click="config.isVisible = true">其它信息
          <i class="iconfont icon-peixunsucai_xiala"></i>
        </div>
      </div>
      <div class="item-module" v-show="config.isVisible">
        <h2>其它信息</h2>
        <ul class="input-list">
          <li class="input-item van-hairline--bottom" v-for="item in otherInfo" :key="item.key" @click="clickHandle(item)">
            <span class="label">{{ item.name + item.unit }}</span>
            <input class="value" type="text" readonly v-model="item.label" :placeholder="item.placeholder+item.name" />
            <span class="icon" :style="{ visibility: item.isInput ? 'hidden' : 'none' }"><i class="iconfont icon-wode-erjizhe"></i></span>
          </li>
        </ul>
        <div class="show-btn" v-show="config.visibleBtn && config.isVisible" @click="config.isVisible = false">收起
          <i class="iconfont icon-peixunsucai_shouqi"></i>
        </div>
      </div>
      <van-popup v-model="showPicker"
      @close="closePickwe"
      position="bottom">
        <ul v-show="selectItem && selectItem.isInput" class="input-module">
          <li class="title">
            <span class="cancel" @click="closePickwe">取消</span>
            <span class="tip">{{ selectItem.placeholder+selectItem.name + selectItem.unit }}</span>
            <span class="confirm" @click="inputChange">确定</span>
          </li>
          <li class="value van-hairline--top">
            <input ref="inputValue" @blur="blurHandler" :type="selectItem.type" :maxlength="selectItem.maxlength" v-model="selectItem.label" placeholder="请输入" />
          </li>
        </ul>
        <van-picker
          show-toolbar
          :title="selectItem.placeholder+selectItem.name"
          ref="picker" 
          v-show="selectItem && !selectItem.isInput"
          :columns="selectItem.columns"
          @cancel="closePickwe"
          @confirm="confirmPopup"
        />
      </van-popup>
    </div>
    <div class="submit van-hairline--top" v-show="!showPicker">
      <span class="cancel-btn" @click="clickJump(false)">取消</span>
      <span class="insert-btn" @click="clickJump(true)">确定插入</span>
    </div>
  </div>
</template>

<script>
import ImageUpload from '@/components/ImageUpload'
import goodService from '@/services/goodService'
import otherAllInfo from './optionInfo'

const config = {
  limit: 3, // 图片上传数量限制
  id: 'upload',
  maxlength: 400, // 描述字段限制
  isVisible: false, // 是否显示其它信息
  visibleBtn: true, // 是否显示其它信息控制按钮
  descTitle: '房屋描述' // 显示房屋描述title
}

const params = {
  title: '',
  description: '',
  imageUrl: ''
}

export default {
  data() {
    let type = this.$route.query.type || 'secondLinker'
    let goodsId = this.$route.query.goodsId
    this.type = type
    this.goodsId = goodsId
    let otherInfo = otherAllInfo.filter(item => {
      item.label = ''
      item.value = ''
      return item.apply.includes(type)
    })
    Object.keys(params).forEach(key => {
      params[key] = ''
    })
    return  {
      loading: false,
      finished: false,
      current: 1,
      size: 10,
      config,
      params,
      otherInfo,
      fileList: [],
      showPicker: false,
      selectItem: {},
      createParams: {}
    }
  },
  components: {
    ImageUpload
  },
  created() {
    if (this.type === 'other') {
      config.visibleBtn = false
      config.isVisible = true
      config.descTitle = '核心卖点'
    } else {
      config.visibleBtn = true
      config.isVisible = false
      config.descTitle = '房屋描述'
    }
    if (this.goodsId) {
      document.title = '编辑商品'
      this.setDataInfo(this.goodsId)
    }
  },
  methods: {
    // 对编辑情况下的数据进行回写
    async setDataInfo(goodsId) {
      let writeData = await goodService.selectById(goodsId)
      let { imageUrl, title, description } = writeData
      this.params = { imageUrl, title, description }
      this.fileList = imageUrl.split(",").map(item => ({ thumb: item, fileUrl: item }))
      this.otherInfo.forEach(item => {
        let keys = item.key
        let value = ''
        keys.split("-").forEach((key, index) => {
          let divide = index ? '/' : ''
          value += divide + writeData[key]
        })
        if (!writeData[keys]) writeData[keys] = value
        if (item.isInput) {
          item.label = writeData[keys]
        } else {
          let label = writeData[keys]
          if (value.includes('/') && !value.includes('-1')) {
            item.label = item.parseShow(label)
          } else if(!value.includes('/') && value != 0){
            item.label = item.columns[0].values[label - 1]
          }
        }
        this.createParams = writeData
      })
    },
    blurHandler() {
      window.scroll(0, 0)
    },
    clickHandle(item) {
      this.selectItem = item
      this.defaultLabel = item.label
      console.log(item)
      // 在选择框进行选择之后，再次点击默认显示上一次选中的数据
      if (!item.isInput && item.label) {
        this.selectItem.columns.forEach((list, index) => {
          let code = item.label
          if (item.dataLocation) code = item.dataLocation(code, index)
          list.defaultIndex = list.values.indexOf(code)
        })
      }
      this.showPicker = true
      this.isEdit = false
      if (item.isInput) {
        this.$nextTick(() => {
          this.$refs.inputValue.focus()
        })
      }
    },
    popupChange(picker, value, index) {
      console.log(value)
    },
    confirmPopup(value, indexs) {
      // console.log(value, indexs)
      // console.log(indexs)
      let alias = value
			if (this.selectItem.plugin) {
				alias = this.selectItem.plugin(value)
      }
      this.selectItem.label = alias
      this.selectItem.value = value

      this.isEdit = true
			this.selectItem.columns.forEach((item, index) =>{
        item.defaultIndex = indexs[index]
      })
      this.showPicker = false
      this.selectItem.getAttr(this.createParams, indexs, value)
    },
    clickJump(bool) {
      if (!bool) {
        this.$router.go(-2)
      } else {
        this.paramsIsEmpty()
      }
    },
    /**
     * 保存前查询是否有必填字段未输入
     * 保存调用保存接口， 更新调用更新接口
     */
    paramsIsEmpty() {
      let bool = false
      this.params.imageUrl = this.fileList.map(item => item.fileUrl).join(",")
      Object.values(this.params).some(item => {
        if (!item) {
          this.$toast("必填项不能为空")
          bool = true
          return true
        }
      })
      if (bool) return false
      if(this.goodsId) {
        this.updateLinker()
      } else {
        this.addLinker()
      }
    },
    selectCurrent(obj, goodsId, type) {
      let current = {}
      current.inlayObjectType = type ? type : obj.type
      current.advertisingImgUrl = obj.imageUrl.split(",")[0]
      current.slogan = obj.title
      current.goodsId = goodsId ? goodsId : obj.goodsId
      window.sessionStorage.setItem("inlayHouse", JSON.stringify(current))
      this.$router.go(-2)
    },
    async addLinker() {
      let obj = Object.assign(this.createParams, this.params)
      try {
        let goodsId = await goodService.addLinker(this.type, obj)
        this.$toast.success("保存成功")
        setTimeout(() => {
          let params = { secondLinker: 2, rentalLinker: 1, other: 3 }
          this.selectCurrent(obj, goodsId, params[this.type])
        }, 300)
      } catch (error) {
        console.log(error)
      }
    },
    async updateLinker() {
      let obj = Object.assign(this.createParams, this.params)
      try {
        await goodService.updateLinker(this.type, obj)
        this.$toast.success("更新成功")
        setTimeout(() => {
          this.selectCurrent(obj)
        }, 300)
      } catch (error) {
        console.log(error)
      }
    },
    inputChange() {
      console.log(123)
      this.isEdit = true
      let { label, key } = this.selectItem
      console.log(this.selectItem)
      this.selectItem.value = label
      this.createParams[key] = label
      this.showPicker = false
    },
    closePickwe() {
      if (!this.isEdit) {
        this.selectItem.label = this.defaultLabel
      }
      this.showPicker = false
		},
  }
}
</script>

<style lang="less" scoped>

.addWares-page {
  background: #F7F9FA;
  .addWares-scroll {
    height: calc(100% - 60px);
    overflow: auto;
  }
  .addWares-height {
    height: 100%;
  }

  .submit {
    height: 60px;
    padding: 8px 16px;
    font-size: 16px;
    display: flex;
    background: #fff;
    justify-content: space-between;
    span {
      width: 146px;
      height: 44px;
      line-height: 44px;
      text-align: center;
      border-radius: 6px;
    }
    .insert-btn {
      color: #fff;
      background: #007AE6;
    }
    .cancel-btn {
      color: #445166;
      background: #E3E9EF;
    }
  }

  .show-btn {
    height: 44px;
    width: 100%;
    background: #F2F8FE;
    text-align: center;
    line-height: 44px;
    font-size: 16px;
    color: #40516F;
    font-weight: bold;
    margin: 4px 0 12px 0;
  }

  .item-module {
    padding: 12px 16px;
    background: #fff;
    margin-bottom: 12px;
    h2 {
      font-size: 20px;
      height: 28px;
      font-weight: bold;
      .icon {
        color: #EB602F;
        font-weight: normal;
        margin: 0 2px;
      }
      .text {
        font-size: 14px;
        line-height: 20px;
        color: #9CA5B5;
      }
    }
    .imageUpload {
      padding-top: 12px;
      /deep/ .image-upload {
        overflow: hidden;
        position: relative;
        .file-item {
          width: 106px;
          height: 106px;
          margin-right: 12px;
          margin-bottom: 12px;
          font-size: 16px;
          .uploading-shade {
            padding-top: 36px;
          }
          .error-shade {
            padding-top: 45px;
          }
          &:nth-child(3n) {
            margin-right: 0px;
          }
        }
        .file-uploads-html5 {
          width: 106px;
          height: 106px;
          margin-bottom: 12px;
          border: 1px solid #9BA4B4;
          .van-icon-plus {
            padding-top: 32px;
          }
        }
      }
    }
    .input-value {
      padding: 12px 0;
      font-size: 0;
      position: relative;
      input {
        border: none;
        width: 100%;
        font-size: 16px;
        line-height: 24px;
        color: #405170;
      }
      textarea {
        width: 100%;
        height: 140px;
        font-size: 14px;
        line-height: 20px;
        padding: 8px;
        color: #405170;
        outline: none;
        -webkit-appearance: none;
        border: 1px solid #CED1D6;
      }
      .limit {
        position: absolute;
        bottom: 12px;
        width: 40px;
        line-height: 20px;
        font-size: 12px;
        right: 0;
        color: #9CA5B5;
        text-align: right;
        padding-right: 4px;
      }
    }
    .input-list {
      padding-bottom: 12px;
      .input-item {
        height: 52px;
        display: flex;
        color: #13284D;
        align-items: center;
        justify-content: space-between;
        .label {
          font-size: 16px;
          line-height: 24px;
          padding-right: 30px;
        }
        .value {
          flex: 1;
          height: 24px;
          border: 0;
          font-size: 14px;
          line-height: 24px;
          text-align: right;
        }
        .icon {
          font-size: 16px;
          color: #C2C7CC;
          text-align: right;
          padding-left: 4px;
        }
      }
    }
  }
  .input-module {
    background: #fff;
    .title {
      display: flex;
      padding: 10px 18px;
      span {
        font-size: 16px;
        line-height: 24px;
      }
      .cancel {
        color: #999;
      }
      .tip {
        flex: 1;
        text-align: center;
        color: #999;
      }
      .confirm {
        color: #007AE6;
      }
    }
    .value {
      height: 52px;
      text-align: center;
      /* line-height: 52px; */
      font-size: 0;
      input {
        width: 200px;
        text-align: center;
        height: 22px;
        line-height: 22px;
        font-size: 14px;
        border: 0;
        margin-top: 12px;
      }
    }

  }
}

</style>